﻿Imports System
Imports System.ComponentModel
Imports Microsoft.Office.Interop
Imports System.Text
Imports System.IO
Imports Microsoft.Office.Interop.Word

Public Class WordAppl

    Public oWordAppl As Microsoft.Office.Interop.Word.Application
    Public oDoc As Microsoft.Office.Interop.Word.Document
    Protected dirLaudosWord As String = System.Configuration.ConfigurationManager.AppSettings("dirLaudosWord")
    Protected dirTemplateword As String = System.Configuration.ConfigurationManager.AppSettings("dirTemplateword")
    Dim wordDoc As Microsoft.Office.Interop.Word.Document

    '------------------------------------------------------------------------
    ' MÉTODO CONSTRUTOR
    '------------------------------------------------------------------------


    Public Sub New()

        oWordAppl = New Word.Application

    End Sub

    Public Property getWordAppl() As Word.Application

        Get
            Return oWordAppl

        End Get

        Set(ByVal value As Word.Application)

            oWordAppl = Nothing
        End Set

    End Property
    '--------------------------------------------------------------------------------------------
    ' ROTINA QUE ABRE O MODELO DO WORD - SE O MODELO NÃO EXISTIR, VAI GERAR ERRO
    '--------------------------------------------------------------------------------------------

    Public Sub Open(ByVal diretorio As String, ByVal arquivo As String)

        Dim path As String = System.Configuration.ConfigurationManager.AppSettings("dirLaudosWord")

        Dim fileName As String = IO.Path.Combine(System.Windows.Forms.Application.StartupPath, path & "\" & diretorio & "\" & arquivo)

        Try

            Dim readOnly1 As Object = False

            Dim isVisible As Object = True

            Dim missing As Object = System.Reflection.Missing.Value

            If Not File.Exists(fileName) Then

                MsgBox("Arquivo " & fileName & " não localizado no respectivo diretório")

            Else

                'oDoc = oWordAppl.Documents.Open(fileName, , readOnly1 )
                oDoc = oWordAppl.Documents.Open(fileName, , readOnly1, , , , , , , , , , True)
                oDoc.Activate()

            End If

        Catch ex As Exception

            Throw ex

        End Try

    End Sub


    '--------------------------------------------------------------------------------------------
    ' ROTINA QUE ABRE O MODELO DO WORD - SE O MODELO NÃO EXISTIR, VAI GERAR ERRO
    '--------------------------------------------------------------------------------------------

    Public Sub OpenModelo(ByVal arquivo As String)

        Dim diretorio As String = System.Configuration.ConfigurationManager.AppSettings("dirTemplateword")

        Dim fileName As String = IO.Path.Combine(System.Windows.Forms.Application.StartupPath, diretorio & "\" & arquivo)

        Try

            Dim readOnly1 As Object = False

            Dim isVisible As Object = True

            Dim missing As Object = System.Reflection.Missing.Value

            If Not File.Exists(fileName) Then

                MsgBox("Arquivo " & fileName & " não localizado no respectivo diretório")

            Else

                ' oDoc = oWordAppl.Documents.Open(fileName)
                oDoc = oWordAppl.Documents.Open(fileName, , readOnly1, , , , , , , , , , True)
                ' oDoc.Activate()

            End If

        Catch ex As Exception

            Throw ex

        End Try

    End Sub
    Public Sub Open()
        Try

            Dim missing As Object = System.Reflection.Missing.Value
            oDoc = oWordAppl.Documents.Add(missing, missing, missing, missing)
            oDoc.Activate()
        Catch ex As Exception

            Throw ex
        End Try
    End Sub

    Public Sub Close()
        Try
            Dim missing As Object = System.Reflection.Missing.Value
            oDoc.Application.Quit(missing, missing, missing)
        Catch ex As Exception

            Throw ex
        End Try
    End Sub

    Public Sub Quit()
        Try
            'Dim missing As Object = System.Reflection.Missing.Value
            'oWordAppl.Application.Quit(missing, missing, missing)
            'oWordAppl = Nothing

            Dim missing As Object = System.Reflection.Missing.Value
            oWordAppl.NormalTemplate.Saved = True
            oWordAppl.Quit()
            oWordAppl = Nothing

        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub Save()
        Try
            oDoc.Save()
            
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub SaveAs(ByVal diretorio As String, ByVal nomeArquivo As String)

        Try
            Dim path As String = System.Configuration.ConfigurationManager.AppSettings("dirLaudosWord")
            Dim missing As Object = System.Reflection.Missing.Value
            Dim fileName As Object = System.IO.Path.Combine(System.Windows.Forms.Application.StartupPath, path & "\" & diretorio & "\" & nomeArquivo)
            generica.criarDiretorio(diretorio)
            oDoc.SaveAs(fileName, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub abrirDocumento(ByVal fileName As String)

        Try

            Dim word As New Word.Application
            With word
                .Documents.Open(fileName)
                .Visible = True
                .WindowState = WdWindowState.wdWindowStateMaximize

            End With

        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Public Sub FindAndReplacement(ByVal strFind As String, ByVal strReplace As String)
        Try
            oWordAppl.Selection.HomeKey(Word.WdUnits.wdStory, Word.WdMovementType.wdExtend)
            With oWordAppl.Selection.Find
                .Text = strFind
                With .Replacement
                    .Text = strReplace
                End With
                .Execute(Replace:=Word.WdReplace.wdReplaceAll)
            End With
        Catch ex As Exception
            Throw ex
        End Try
    End Sub



    Public Sub criaPreambulo(ByVal ucPreambulo As ucPreambulo)

        Dim iLoop, iTotal As Integer
        Dim lista As New List(Of regionalVO)
        Dim regionalBo As New regionalBO
        Dim regional As New regionalVO
        Dim oRange As Microsoft.Office.Interop.Word.Range
        Dim achou As Boolean = False

        '---------------------------------------------
        ' ALTERAÇÃO PARA ATENDER SÃO SEBASTIÃO DO PARAÍSO
        ' O CERTO SERIA ALTERACAO NA BASE DE DADOS
        '--------------------------------------------



        Try
            lista = regionalBo.getRegionais

            For Each elemento As regionalVO In lista

                If elemento.CIDADE_REGIONAL = 762 Then

                    achou = True
                    Exit For
                End If

            Next

            If Not achou Then
                regional = lista(0)
            Else
                regional = lista(1)
            End If


            '----------------------------------------------------------------------------------------
            ' PREENCHE O CABEÇALHO
            '----------------------------------------------------------------------------------------
            For Each oRange In oDoc.StoryRanges
                ' We only focus on Header & Body
                If oRange.StoryType = Word.WdStoryType.wdPrimaryHeaderStory Or _
                   oRange.StoryType = Word.WdStoryType.wdMainTextStory Then
                    For iLoop = 0 To iTotal
                        With oRange.Find
                            .Text = "<<LAUDO>>"
                            .Replacement.Text = ucPreambulo.getNumeroLaudoFormatado
                            .Forward = True
                            .Wrap = Word.WdFindWrap.wdFindContinue
                            .Execute(Replace:=Word.WdReplace.wdReplaceAll)

                            .Text = "<<num_depto>>"
                            .Replacement.Text = regional.DEPARTAMENTO.NUMERO_DEPARTAMENTO
                            .Forward = True
                            .Wrap = Word.WdFindWrap.wdFindContinue
                            .Execute(Replace:=Word.WdReplace.wdReplaceAll)

                            .Text = "<<num_regional>>"
                            .Replacement.Text = regional.NUMERO_REGIONAL
                            .Forward = True
                            .Wrap = Word.WdFindWrap.wdFindContinue
                            .Execute(Replace:=Word.WdReplace.wdReplaceAll)

                            .Text = "<<cidade_regional>>"
                            .Replacement.Text = frmLogin.usuarioLogado.SECAO.DESC_SECAO
                            .Forward = True
                            .Wrap = Word.WdFindWrap.wdFindContinue
                            .Execute(Replace:=Word.WdReplace.wdReplaceAll)

                        End With
                    Next
                End If
            Next
            '----------------------------------------------------------------------------------------
            ' PREENCHE O PREAMBULO
            '---------------------------------------------------------------------------------------
            FindAndReplacement("<<autoridade>>", ucPreambulo.getNomeAutoridadePrefixo)
            FindAndReplacement("<<natureza>>", ucPreambulo.getDescNaturezaPericia)
            '   FindAndReplacement("<<naturezaDelitoTexto>>", ucPreambulo.getNaturezaDelito)
            FindAndReplacement("<<local>>", ucPreambulo.getLocal)
            FindAndReplacement("<<data>>", ucPreambulo.getDataRegistroFormatada.ToLower)
            FindAndReplacement("<<requisicao>>", ucPreambulo.getRequisicao)
            FindAndReplacement("<<referencia>>", ucPreambulo.getReferencia)
            FindAndReplacement("<<titIndiciado>>", ucPreambulo.getDescTipoAutor)
            FindAndReplacement("<<indiciado>>", ucPreambulo.getIndiciado)
            FindAndReplacement("<<vitima>>", ucPreambulo.getVitima)
            FindAndReplacement("<<destino>>", ucPreambulo.getNomeDestinoSelecionado)
        Catch ex As Exception
            Throw ex
        End Try
    End Sub

    Public Sub criaAssinatura(ByVal ucPreambulo As ucPreambulo)

        Dim assinatura As New StringBuilder
        Try
            assinatura.Append(ucPreambulo.getCidadeRegional).Append(", ").Append(ucPreambulo.getDataFormatadaAssinatura).Append(".")
            FindAndReplacement("<<assinatura>>", assinatura.ToString)
            FindAndReplacement("<<perito>>", ucPreambulo.getNomePeritoSelecionado & " - Perito Criminal")
            FindAndReplacement("<<masp>>", "MASP: " & ucPreambulo.getMaspPeritoSelecionado())
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Public Sub insereTexto(ByVal texto As String)

        oWordAppl.Selection.TypeText(texto)

    End Sub

    Public Sub insereTexto()

        With oWordAppl

            .Selection.TypeText(Text:="escrevi um texto aqui")
            .Selection.TypeParagraph()
            .Selection.TypeText(Text:="depois outra linha")
            .Selection.TypeParagraph()
            .Selection.TypeText(Text:="e depois mais outra")
            .Selection.TypeParagraph()
            .Selection.TypeParagraph()
            .Selection.TypeParagraph()
            .Selection.TypeParagraph()
            .Selection.TypeText(Text:="agora aqui")
            .Selection.TypeParagraph()
        End With



        'oWordAppl.Selection.Range.MoveEnd()




    End Sub

    Public Sub insereHtml(ByVal html As StringBuilder)


        oWordAppl.Selection.TypeText(html.ToString)
        oWordAppl.Selection.TypeParagraph()

    End Sub

    Public Sub preencheTable()
        Try

            With oWordAppl.Selection.Tables(1)

                With .Rows.Last

                    .Cells(1).Range.Text = "valor01"
                    .Cells(1).Range.Text = "valor02"

                End With

                .Rows.Add()

            End With
        Catch ex As Exception
            Throw ex
        End Try



    End Sub
    Public Sub geraContatos(ByVal query As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), ByVal indice As Integer)

        Dim oTable As Word.Table
        Dim i As Integer = 0
        Dim x As Integer = 2

        oTable = oDoc.Tables.Item(indice)

        For Each elemento In query
            oTable.Rows.Add()
            With oTable


                .Cell(x, 1).Range.Text = elemento.Attribute("label").Value
                .Cell(x, 2).Range.Text = elemento.Descendants("NUMBER").Value
                .Cell(x, 3).Range.Text = elemento.Descendants("NUMBER").Value
                x = x + 1

            End With
        Next

    End Sub


    Public Sub geraContatos(ByVal tabela As System.Data.DataTable, ByVal indice As Integer)

        Dim oTable As Word.Table
        Dim i As Integer = 0
        Dim x As Integer = 2
        Dim ind As Integer
        Dim linha As DataRow

        linha = tabela.Rows(0)

        Dim nome, telefone As Integer


        For ind = 0 To 10
            If linha(ind).Equals("label") Then
                nome = ind
            End If
            If linha(ind).Equals("unspecified") Then
                telefone = ind
                Exit For
            End If
        Next

        Try

            'For Each linha In tabela.Rows
            '    oTable.Rows.Add()
            '    With oTable
            '        .Cell(x, 1).Range.Text = linha(5).ToString & " " & linha(7).ToString
            '        .Cell(x, 2).Range.Text = linha(8).ToString
            '        '.Cell(x, 3).Range.Text = tabela.Rows(13).ToString
            '        x = x + 1
            '    End With
            'Next

            oTable = oDoc.Tables.Item(indice)
            For Each linha In tabela.Rows
                oTable.Rows.Add()
                With oTable
                    .Cell(x, 1).Range.Text = linha(nome).ToString
                    .Cell(x, 2).Range.Text = linha(telefone).ToString
                    '.Cell(x, 3).Range.Text = tabela.Rows(13).ToString
                    x = x + 1
                End With
            Next

        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Public Sub geraChamadas(ByVal tabela As System.Data.DataTable, ByVal indice As Integer)
        Dim oTable As Word.Table
        Dim i As Integer = 0
        Dim x As Integer = 2
        Dim ind As Integer
        Dim linha As DataRow
        linha = tabela.Rows(0)
        Dim nome, telefone, data As Integer


        For ind = 0 To 10
            If linha(ind).Equals("unspecified") Then
                telefone = ind
            End If
            If linha(ind).Equals("date") Then
                data = ind
            End If
            If linha(ind).Equals("label") Then
                nome = ind
                '  Exit For
            End If
        Next
        Try
            oTable = oDoc.Tables.Item(indice)
            For Each linha In tabela.Rows
                oTable.Rows.Add()
                With oTable
                    .Cell(x, 1).Range.Text = x + 1
                    .Cell(x, 2).Range.Text = linha(nome).ToString
                    .Cell(x, 3).Range.Text = linha(telefone).ToString
                    .Cell(x, 4).Range.Text = linha(data).ToString
                    x = x + 1
                End With
            Next
        Catch ex As Exception
            Throw ex
        End Try
    End Sub


    Public Sub geraMensagens(ByVal tabela As System.Data.DataTable, ByVal indice As Integer)

        Dim oTable As Word.Table
        Dim i As Integer = 0
        Dim x As Integer = 2
        oTable = oDoc.Tables.Item(indice)
        Try
            For Each linha In tabela.Rows
                oTable.Rows.Add()
                With oTable
                    .Cell(x, 1).Range.Text = linha(1).ToString
                    .Cell(x, 2).Range.Text = linha(3).ToString
                    .Cell(x, 3).Range.Text = linha(2).ToString
                    .Cell(x, 4).Range.Text = linha(5).ToString
                    x = x + 1
                End With
            Next
        Catch ex As Exception
            Throw ex
        End Try
    End Sub


    Public Sub geraChamadas(ByVal query As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), ByVal indice As Integer)

        Dim oTable As Word.Table
        Dim i As Integer = 0
        Dim x As Integer = 2

        oTable = oDoc.Tables.Item(indice)

        Try
            For Each elemento In query
                oTable.Rows.Add()
                With oTable
                    .Cell(x, 1).Range.Text = elemento.Attribute("index").Value
                    .Cell(x, 2).Range.Text = elemento.Attribute("label").Value
                    .Cell(x, 3).Range.Text = elemento.Descendants("NUMBER").Value
                    .Cell(x, 4).Range.Text = elemento.Descendants("TIMESTAMP").Value
                    x = x + 1
                End With
            Next
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Public Sub geraMensagens(ByVal query As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement), ByVal indice As Integer, ByVal texto As String)

        Dim oTable As Word.Table
        Dim i As Integer = 0
        Dim x As Integer = 2

        oTable = oDoc.Tables.Item(indice)

        Try

            For Each elemento In query
                oTable.Rows.Add()
                With oTable
                    .Cell(x, 1).Range.Text = texto
                    .Cell(x, 2).Range.Text = elemento.Attribute("from").Value

                    If texto.Equals("Recebida") Then
                        .Cell(x, 3).Range.Text = elemento.Attribute("received").Value
                    Else
                        .Cell(x, 3).Range.Text = elemento.Attribute("sent").Value
                    End If
                    .Cell(x, 4).Range.Text = elemento.Value
                    x = x + 1

                End With
            Next

        Catch ex As Exception
            Throw ex
        End Try

    End Sub


    Public Function geraEMEI(ByVal query As System.Collections.Generic.IEnumerable(Of System.Xml.Linq.XElement)) As String

        Try
            Return query.First.Value
        Catch ex As Exception
            Return "Erro na leitura do imei"

        End Try
    End Function

    Public Sub dadosTabela(ByVal objTable As DataTable, ByVal indice As Integer)


        'Dim oTable As Word.Table
        'Dim i As Integer = 0
        'Dim x As Integer = 2

        'oTable = oDoc.Tables.Item(indice)

        'For i = 1 To objTable.Rows.Count - 1
        '    oTable.Rows.Add()
        'Next


        'With oTable
        '    For Each objrow As DataRow In objTable.Rows
        '        .Cell(x, 1).Range.Text = objrow("coluna1")
        '        .Cell(x, 2).Range.Text = objrow("coluna2")
        '        .Cell(x, 3).Range.Text = objrow("coluna3")
        '        x = x + 1
        '    Next

        'End With

    End Sub

    Public Sub insereDadosTabelaTelefonia(ByVal objTable As DataTable, ByVal indice As Integer)


        'Dim oTable As Word.Table
        'Dim i As Integer = 0

        'oTable = oDoc.Tables.Item(indice)
        'For i = 1 To objTable.Rows.Count - 1

        '    oTable.Rows.Add()

        'Next

        'With oTable

        '    For Each objrow As DataRow In objTable.Rows

        '        Try

        '            .Cell(i, i).Range.Text = objrow.Item("indice")
        '            .Cell(i, i + 1).Range.Text = objrow.Item("nome")
        '            .Cell(i, i + 2).Range.Text = objrow.Item("telefone")
        '            i = i + 1

        '        Catch ex As Exception

        '            Exit For

        '        End Try
        '    Next

        'End With

    End Sub



    Public Sub insereLista(ByVal texto As String)
        '
        ' teste Macro
        '
        '
        oWordAppl.Selection.TypeText(Text:=texto)
        oWordAppl.Selection.TypeParagraph()

    End Sub


    Public Sub RunMacro(ByVal oApp As Object, ByVal oRunArgs As Object())
        oApp.[GetType]().InvokeMember("Run", System.Reflection.BindingFlags.[Default] Or System.Reflection.BindingFlags.InvokeMethod, Nothing, oApp, oRunArgs)
    End Sub

    Public Sub insereDadosDrogas(ByVal dataGrid As DataGridView, ByVal totalTabelas As Integer, _
                                 Optional totun As Boolean = False, _
                                 Optional ehFalso As Boolean = False)
        Dim oTable As Word.Table = Nothing
        Dim contTabelas As Integer = 1
        Try

            For contTabelas = 1 To totalTabelas
                oTable = oDoc.Tables.Item(contTabelas)
                For i = 1 To dataGrid.Rows.Count - 1
                    oTable.Rows.Add()
                Next
                If contTabelas = 1 And totun Then
                    oTable.Rows.Add()
                End If

                If contTabelas = 2 And ehFalso Then
                    oTable.Rows.Add()
                End If

                With oTable
                    For Each objrow As DataGridViewRow In dataGrid.Rows
                        Try
                            .Cell(objrow.Index + 1, 1).Range.Text = objrow.Cells(contTabelas - 1).Value.ToString
                        Catch ex As Exception
                            Exit For
                            generica.gravaErro(ex)
                        End Try
                    Next
                    If contTabelas = 1 Then
                        If totun Then
                            .Cell(oTable.Rows.Count + 1, 1).Range.Text = "Observação: Entenda-se por " & Chr(34) & "in totum" & Chr(34) & " a massa total do material apreendido, ou seja, a massa da substância acrescida da massa da embalagem, visando manter a característica e forma em que a substância foi apreendida na origem."
                        End If
                    End If

                    If contTabelas = 2 Then
                        If ehFalso Then
                            .Cell(oTable.Rows.Count + 1, 1).Range.Text = "Em que pese os característicos divergentes observados, foi constatado que o documento questionado não apresenta características de cópia grosseira, uma vez que o falsário conseguiu reproduzir com nitidez as características macroscópicas existentes nas cédulas autênticas."
                        End If
                    End If

                End With
            Next
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Public Sub insereDadosTabela(ByVal dataGrid As DataGridView, ByVal totalTabelas As Integer)
        Dim oTable As Word.Table = Nothing
        Dim contTabelas As Integer = 1
        Try
            For contTabelas = 1 To totalTabelas
                oTable = oDoc.Tables.Item(contTabelas)
                For i = 1 To dataGrid.Rows.Count - 1
                    oTable.Rows.Add()
                Next

                With oTable
                    For Each objrow As DataGridViewRow In dataGrid.Rows
                        Try
                            .Cell(objrow.Index + 1, 1).Range.Text = objrow.Cells(contTabelas - 1).Value.ToString
                        Catch ex As Exception
                            Exit For
                            generica.gravaErro(ex)
                        End Try
                    Next
                End With
            Next
        Catch ex As Exception
            Throw ex
        End Try

    End Sub


    Public Sub insereTabelaPapelMoeda(ByVal dataGrid As DataGridView, ByVal totalTabelas As Integer, Optional documentoFalso As Boolean = False)
        Dim oTable As Word.Table = Nothing
        Dim contTabelas As Integer = 1
        Try
            For contTabelas = 1 To totalTabelas
                oTable = oDoc.Tables.Item(contTabelas)
                For i = 1 To dataGrid.Rows.Count - 1
                    oTable.Rows.Add()
                Next
                If contTabelas = 1 Then
                    oTable.Rows.Add()
                End If

                With oTable
                    For Each objrow As DataGridViewRow In dataGrid.Rows
                        Try
                            If documentoFalso Then

                                If CInt(objrow.Cells(0).Value) > 1 Then
                                    .Cell(objrow.Index + 1, 1).Range.Text = "São falsas as cédulas com valor impresso de" & objrow.Cells(1).Value.ToString & " , numeração " & objrow.Cells(2).Value.ToString & ", uma vez que não possui os elementos de segurança peculiares às notas autênticas. "
                                Else
                                    .Cell(objrow.Index + 1, 1).Range.Text = "É falsa a cédula com valor impresso de" & objrow.Cells(1).Value.ToString & " , numeração " & objrow.Cells(2).Value.ToString & ", uma vez que não possui os elementos de segurança peculiares às notas autênticas. "
                                End If
                            Else

                                If CInt(objrow.Cells(0).Value) > 1 Then
                                    .Cell(objrow.Index + 1, 1).Range.Text = "São autêtncias as cédulas com valor impresso de" & objrow.Cells(1).Value.ToString & " , numeração " & objrow.Cells(2).Value.ToString & ", uma vez que não possui os elementos de segurança peculiares às notas autênticas. "
                                Else
                                    .Cell(objrow.Index + 1, 1).Range.Text = "É autêntica a cédula com valor impresso de" & objrow.Cells(1).Value.ToString & " , numeração " & objrow.Cells(2).Value.ToString & ", uma vez que não possui os elementos de segurança peculiares às notas autênticas. "
                                End If

                            End If
                        Catch ex As Exception
                            Exit For
                            generica.gravaErro(ex)
                        End Try
                    Next
                    If contTabelas = 1 Then
                        If documentoFalso Then
                            .Cell(oTable.Rows.Count + 1, 1).Range.Text = "Em que pese os característicos divergentes observados, foi constatado que o documento questionado não apresenta características de cópia grosseira, uma vez que o falsário conseguiu reproduzir com nitidez as características macroscópicas existentes nas cédulas autênticas."
                        End If
                    End If
                End With
            Next
        Catch ex As Exception
            Throw ex
        End Try

    End Sub

    Public Function insereTabela(ByVal dataGrid As DataGridView) As Double

        Dim row As Integer = 2
        Dim total As Double = 0
        Dim itens As Integer = 0
        Dim oTable As Word.Table
        Dim y As Integer

        Try


            oTable = oDoc.Tables.Item(1)

            For i = 1 To dataGrid.Rows.Count - 1

                oTable.Rows.Add()

            Next

            With oTable

                For Each objrow In dataGrid.Rows


                    total = total + (CDbl(CType(objrow, DataGridViewRow).Cells(0).Value) * CDbl(CType(objrow, DataGridViewRow).Cells(2).Value))

                    Try
                        For y = 1 To oTable.Columns.Count

                            '-----------------------------------------------------------------------------
                            ' O INDICE DE UMA TABELA WORD COMEÇA COM O ÍNDICE 1 - NO CASO A INSERÇÃO DEVERÁ COMEÇAR NA SEGUNDA LINHA DA TABELA
                            '-----------------------------------------------------------------------------

                            If y = 1 Then

                                .Cell(row, y).Range.Text = String.Format("{0:C}", CType(objrow, DataGridViewRow).Cells(y - 1).Value)
                                itens = itens + CType(objrow, DataGridViewRow).Cells(y - 1).Value

                            ElseIf y = 3 Then

                                .Cell(row, y).Range.Text = String.Format("{0:C}", CDbl(CType(objrow, DataGridViewRow).Cells(y - 1).Value))


                            Else

                                .Cell(row, y).Range.Text = String.Format("{0:C}", CType(objrow, DataGridViewRow).Cells(y - 1).Value)

                            End If

                        Next

                    Catch ex As Exception

                        Exit For
                        generica.gravaErro(ex)
                    End Try
                    row = row + 1
                Next

            End With
            With oTable

                oTable.Rows.Add()
                '.Cell(row, 1).Range.Text = itens
                .Cell(row, 2).Range.Text = String.Empty
                .Cell(row, 3).Range.Text = String.Empty
                .Cell(row, 4).Range.Text = String.Format("{0:C}", total)
                oTable.Rows(row).Range.Font.Color = Word.WdColor.wdColorDarkRed

            End With


        Catch ex As Exception
            Throw ex
        End Try
        Return total
    End Function

End Class
